package com.novel.download.service.impl;

import com.novel.download.controller.resp.CatalogueResp;
import com.novel.download.controller.resp.SearchResp;
import com.novel.download.service.NovelService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service("novelService")
public class NovelServiceImplCom implements NovelService {

    private static Collection<NovelService> novelServiceList;

    @Override
    public String getName() {
        return null;
    }

    public Map<String, Boolean> ping() {
        if (CollectionUtils.isEmpty(novelServiceList)) {
            return new HashMap<>();
        }
        HashMap<String, Boolean> result = new HashMap<>();
        novelServiceList.forEach(novelService -> {
            Map<String, Boolean> ping = novelService.ping();
            result.putAll(ping);
        });
        return result;
    }

    public Map<String, List<SearchResp>> search(String bookName) {
        if (CollectionUtils.isEmpty(novelServiceList)) {
            return new HashMap<>();
        }
        HashMap<String, List<SearchResp>> result = new HashMap<>();
        for (NovelService novelService : novelServiceList) {
            Map<String, List<SearchResp>> ping = novelService.search(bookName);
            if (Objects.nonNull(ping)) {
                result.putAll(ping);
            }
        }
        return result;
    }

    @Override
    public CatalogueResp catalogue(String url, String net) {
        for (NovelService novelService : novelServiceList) {
            if (net.equals(novelService.getName())) {
                return novelService.catalogue(url, net);
            }
        }
        return null;
    }

    @Override
    public void download(String url, String from, String net, HttpServletResponse response) throws Exception {
        for (NovelService novelService : novelServiceList) {
            if (net.equals(novelService.getName())) {
                novelService.download(url, from, net, response);
            }
        }
    }

    @Component
    static class AnimalTest implements ApplicationContextAware {
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            novelServiceList = applicationContext.getBeansOfType(NovelService.class).values();
            novelServiceList.removeIf(s -> s instanceof NovelServiceImplCom);
        }
    }
}
